<template>
    <n-scrollbar x-scrollable style="max-height: 100vh">
        <CommonPage>
            <div>
                <n-form ref="form"
                        :model="searchCondition"
                        label-placement="left"
                        label-align="right"
                        label-width="80px"
                        :show-require-mark="false">
                    <div>
                        <div class="grid md:flex md:flex-wrap md:gap-x-1">
                            <n-form-item style="margin-left: 10px">
                                <label style="width: 60px;">操作人：</label>
                                <n-select v-model:value="searchCondition.adminId" :options="admins" />
                            </n-form-item>
                            <n-form-item style="margin-left: 10px">
                                <label style="width: 70px;">操作类型:</label>
                                <n-select v-model:value="searchCondition.type" :options="types" />
                            </n-form-item>
                            <n-form-item  style="margin-left: 10px">
                                <n-button type="primary" @click="searchByCondition">筛选</n-button>
                            </n-form-item>
                            <n-form-item  style="margin-left: 10px">
                                <n-button type="error" @click="deleteSelectProduct">批量删除</n-button>
                            </n-form-item>
                          <n-form-item style="margin-left: 10px">
                            <n-button @click="exportListInfo"
                                      type="primary">
                              导出
                            </n-button>
                          </n-form-item>
                        </div>
                    </div>
                </n-form>
            </div>
            <AddCategoryForm :option="option" @update-page="searchByCondition" :show="showForm" :onClose="handleClose" />
            <n-data-table
                    remote
                    :single-line="false"
                    ref="table"
                    :columns="columns"
                    :data="logList"
                    :loading="loading"
                    :pagination="paginationReactive"
                    :row-key="rowKey"
                    :scroll-x="900"
                    @update:checked-row-keys="handleCheck"
            />
        </CommonPage>
    </n-scrollbar>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import api from '@/api/admin';
import LogActions from "@/views/admin/system/system-setting/components/log-actions.vue";
import {useUserStore} from '@/store';
import {useRouter} from 'vue-router';

import {NButton} from 'naive-ui'


const showForm = ref(false);
const handleClose = () => {
showForm.value = false;
};
const userStore = useUserStore()
const router = useRouter()
const loading = ref(true)
const logList = ref([])
const range = ref(null)
const value = ref("全部")
const checkedRowKeysRef = ref([]);
const option = ref([
])
const searchCondition = ref({
type: '全部',
adminId: -1
});
const admins = ref([])
admins.value.push({
label:'全部',
value:-1,
})
const types = [
    {
        label: "全部",
        value: "全部"
    },
    {
        label: "登录",
        value: "登录"
    },
    {
        label: "注册",
        value: "注册"
    },
    {
        label: "采购",
        value: "采购"
    },
    {
        label: "产品",
        value: "添加产品"
    },
    {
        label: "物流",
        value: "添加产品"
    },
]
const columns = [
    {
      type: 'selection',
      fixed: 'left',
    },
    {
      key: 'colId',
      title: '序号',
      width: 60,
    },
    {
      key: 'adminName',
      title: '操作人',
      width: 80,
    },
    {
      key: 'adminRole',
      title: '操作人角色',
      width: 80,
    },

    {
      key: 'type',
      title: '操作类型',
      width: 100,
      align:'center',
    },
    {
      key: 'content',
      title: '操作内容',
      width: 100,
      align:'center',
    },
    {
      key: 'createTime',
      title: '操作时间',
      width: 100,
      align:'center',
    },
    {
      key: 'operation',
      title: '操作',
      width: 100,
      render(row) {
        return h(
            LogActions,
          {
            onClickDelete: () => onDeleteProductCategory(row),
            onClickEdit: () => onEditProductCategory(row),
          }
        );
      }
    },
]
let total = 0
const paginationReactive = reactive({
    page: 1,
    pageSize: 20,
    showSizePicker: true,
    pageSizes: [20, 50, 100],
    itemCount:0,
    prefix: () => {
      return '查询出 ' + total + '条记录';
    },
    onChange: (page) => {
      paginationReactive.page = page;
      queryByPage()
    },
    onUpdatePageSize: (pageSize) => {
      paginationReactive.pageSize = pageSize;
      paginationReactive.page = 1;
      queryByPage()
    }
});
const handleCheck = (rowKeys) => {
    checkedRowKeysRef.value = rowKeys;
}
const deleteSelectProduct = () => {
    if(checkedRowKeysRef.value.length <= 0) {
      $message.error("当前并未选择日志！")
      return
    }
    $dialog.confirm({
      title: '警告',
      content: '您确定删除当前所选日志？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const ids = checkedRowKeysRef.value.join(",")
        loading.value = true
        try {
          const res = await api.deleteLogs({params:{ids}})
          if(res.code === 200) {
            $message.success("删除所选日志成功！")
            await searchByCondition()
          }
          else {
            $message.error(res.message)
          }
        } catch (err) {
          $message.error("删除所选日志失败！")
        }finally{
          loading.value = false
        }
      },
    })
}
const searchByCondition = async () => {
    loading.value = true
    try {
      paginationReactive.page = 1;
      const res = await api.findPageLog({
        params: {
          ...searchCondition.value,
          pageNum: paginationReactive.page,
          pageSize: paginationReactive.pageSize,
        }
      })
      if(res.code === 200) {
        total = res.data.total
        paginationReactive.itemCount = total
        const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
        logList.value = res.data.records.map((item,i)=>{
          return {...item,
            colId: baseCount + i + 1,
          }
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("查询日志失败！")
    }finally{
      loading.value = false
    }
}
const exportListInfo = async () => {
    const res = await api.exportLog({
      adminId: searchCondition.value.adminId,
      type: searchCondition.value.type,
    })
    const contentDisposition = res.headers["content-disposition"]
    // console.log(res)
    let original_fileName = ""
    if(contentDisposition) {
      const uri = res.headers["content-disposition"].split("=")[1]
      original_fileName = window.decodeURI(uri)
    }
    const blob = new Blob([res.data], {type: "application/vnd.ms-excel"});
    if(window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, original_fileName);
    } else{
      const fileName = original_fileName;
      const elink = document.createElement('a')
      document.body.appendChild(elink)
      elink.download= fileName;
      elink.style.display ="none"
      elink.href  = window.URL.createObjectURL(blob)
      elink.click()
      window.URL.revokeObjectURL(elink.href)
      document.body.removeChild(elink)
    }
}
const onDeleteProductCategory = async (productCategory) => {
    $dialog.confirm({
      title: '警告',
      content: '您确定删除当前日志？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        const {id} = productCategory
        loading.value = true
        try {
          const res = await api.deleteLog({id})
          if(res.code === 200) {
            $message.success("删除日志成功！")
            await searchByCondition()
          }
          else {
            $message.error(res.message)
          }
        } catch (err) {
          $message.error("删除日志失败！")
        }finally{
          loading.value = false
        }
      }
    })
}
const onEditProductCategory = async (productCategory) => {
    const {id} = productCategory
    await router.push({name: 'AdminLogDetail', params: {productCategoryId: id}});
}
const queryByPage = async () => {
    loading.value = true
    try {
      const res = await api.findPageLog(
        {
          params:{
            pageNum:paginationReactive.page,
            pageSize:paginationReactive.pageSize,
          }
        })
      if(res.code === 200) {
        total = res.data.total
        paginationReactive.itemCount = total
        const baseCount = (paginationReactive.page - 1)*paginationReactive.pageSize
        logList.value = res.data.records.map((item,i)=>{
          return {...item,
            colId: baseCount + i + 1,
          }
        })
        // 调用函数生成n-cascader的options
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取日志失败！")
    }finally{
      loading.value = false
    }
}
const queryAdminList = async () => {
    loading.value = true
    try {
      const res = await api.findAdminsInProductCategory()
      if(res.code === 200) {
        res.data.map((item)=>{
          admins.value.push({
            label: item.name,
            value: item.id
          })
        })
      }
      else {
        $message.error(res.message)
      }
    } catch (err) {
      $message.error("获取管理员信息失败！")
    }finally{
      loading.value = false
    }
}
const rowKey = (rowData) => {
    return rowData.id
}
onMounted(()=>{
    queryAdminList()
    queryByPage()
})
</script>
<style scoped>
    :deep(.n-data-table-th__title),
    :deep(.n-data-table-td) {
        text-align: center;

    }
    :deep(.n-select) {
        width: 120px !important;
    }

    :deep(.two-line-description) {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 2; /* 控制显示的行数 */
        overflow: hidden;
    }
</style>
